
#include "../channel_common/ChannelCommon.h"

#include <stdlib.h>
#include <iostream>
#include <fstream>

#include "../common/Argv.h"
#include "../common/StringUtils.h"
#include "../logger/logger.h"
#include "../channel_common/ChannelCommon.h"
#include "../channel_common/BrokerQueue.h"
#include "../IPC/ClientSocket.h"
#include "../middleware/CommunicationVendedor.h"
#include "../channel_common/routing_tables/RoutingService.h"

int main(int argc, char **argv)
{
	//Toma argumentos (main)
	Argv args(argv);

	char buffer[TAM_BUFFER];
	std::string brokerName;
	std::string hostName;

	if (args.getArgc() != 3)
	{
		std::cout << "Error: Cantidad de parametros invalida: "<<args.getArgc()<<std::endl;
		exit(1);
	}

	ipc::ClientSocket socketSalida(args.getArgAsInt(1));
	brokerName = args.getArg(2);

	channel::BrokerQueue brokerQueue(brokerName);
	channel::ChannelMessage message;

	channel::StartComunicationMessage startMsg;

	socketSalida.receive(buffer,TAM_BUFFER);

	memcpy(&startMsg, buffer,	sizeof(channel::StartComunicationMessage));

	hostName=startMsg.channelName;

	CLogger::create("CS Broker:"+brokerName+" host:"+hostName);

	CLogger::log("Se recibio el hostName:"+hostName,LogLevelEnum::INFO);

	int mType = channel::RoutingService::registerHost(brokerName,hostName);

	bool deboSeguir = true;
	while (deboSeguir)
	{
		brokerQueue.recvFromReceiver(mType,message);

		CLogger::log("Se obtuvo:" +
				StringUtils::NumberToString(message.destino),LogLevelEnum::DEBUG);


		memcpy(buffer, &message, sizeof(message));

		try{
			socketSalida.send(buffer, TAM_BUFFER);
		}
		catch(Exception &e)
		{
			brokerQueue.sendToTransmiter(mType,message);
			CLogger::log("Se detecto que el canal se cerro del otro lado",LogLevelEnum::WARN);
			exit(1);
		}

		//TODO ver que hago con el resto de los tipos
		if (message.tipo == channel::CHANNEL_END_MSG)
			deboSeguir = false;
	}
	
	CLogger::log("Finalizando canal salida broker.");
	
	socketSalida.close();
}

